package com.example.reviewdemo.utils;

import android.util.Log;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class HttpUtil {

    private static final String URL = "https://www.wanandroid.com/article/list/1/json";
    private static InputStreamReader inputStreamReader;
    private static BufferedReader bufferedReader;

    public static String doGet(String urlStr) {
        String result = "";
        //连接网络
        HttpURLConnection httpURLConnection = null;
        try {
            URL url = new URL(urlStr);
            httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setConnectTimeout(5000);
            httpURLConnection.setRequestMethod("GET");

            //读取数据
            InputStream inputStream = httpURLConnection.getInputStream();
            inputStreamReader = new InputStreamReader(inputStream);

            StringBuilder stringBuilder = new StringBuilder();
            bufferedReader = new BufferedReader(inputStreamReader);

            String line = "";
            while ((line = bufferedReader.readLine()) != null) {
                stringBuilder.append(line);
            }
            result = stringBuilder.toString();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }finally {
            //释放资源
            if (httpURLConnection != null) {
                httpURLConnection.disconnect();
            }

            if (inputStreamReader != null) {
                try {
                    inputStreamReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            if (bufferedReader != null) {
                try {
                    bufferedReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }


        return result;

    }


    public static String getResult(){
        String result = doGet(URL);
//        Log.d("xiaoxulu", "result: "+result);
        return result;
    }
}
